<?php

class UserController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/preview';

    /**
     * Declares class-based actions.
     */
    public function actions() {
        return array(
            // captcha action renders the CAPTCHA image displayed on registration
            'captcha' => array(
                'class' => 'CCaptchaAction',
                'backColor' => 0xFFFFFF,
                'testLimit' => 2,
            ),
        );
    }

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('create', 'captcha', 'activate', 'resetPassword'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('update', 'index', 'view'),
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $this->layout = '//layouts/guest';

        $model = new User;

        // Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($model);

        $transaction = $model->dbConnection->beginTransaction();

        if (isset($_POST['User'])) {
            try
            {
                $model->attributes = $_POST['User'];

                if ($model->save()) {
                    Yii::app()->mailer->sendMail('Welcome to Notebuddy! Email Activation',
                        array(Yii::app()->params['adminEmail'] => 'Notebuddy Team'),
                        array($model->email,),
                            "$model->username, thank you for registering at Notebuddy! <br /><br />
                                        In order to login, you need to activate your account. You can do so by clicking the link below: <br />" .
                                    'http://localhost' . CController::createUrl('user/activate', array('id' => $model->id, 'key' => $model->activation_key)) . " <br />
                                 ");

                    $transaction->commit();

                    $loginUrl = CHtml::link('here', CController::createUrl('site/login'));
                    Yii::app()->user->setFlash('register-success', "You have successfully registered! Please click $loginUrl to login.");
                    $this->refresh();
                }
            }
            catch (Exception $e)
            {
                $transaction->rollBack();
            }
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        $transaction = $model->dbConnection->beginTransaction();

        if (isset($_POST['User'])) {
            try
            {
                $model->attributes = $_POST['User'];

                if ($model->oldPassword && $model->newPassword) {
                    $model->password = $model->newPassword;
                    if ($model->save()) {
                        $transaction->commit();
                        Yii::app()->user->setFlash('update-success', 'Your password has been updated.');
                        $this->refresh();
                    }
                } else {
                    if ($model->save(true, array('email'))) {
                        $transaction->commit();
                        Yii::app()->user->setFlash('update-success', 'Your email has been updated.');
                        $this->refresh();
                    }
                }
            }
            catch (Exception $e)
            {
                $transaction->rollBack();
            }
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('User');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new User('search');
        $model->unsetAttributes(); // clear any default values
        if (isset($_GET['User']))
            $model->attributes = $_GET['User'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = User::model()->findByPk((int) $id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'user-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    /**
     * Activate the user account
     */
    public function actionActivate($id, $key) {
        $this->layout = '//layouts/guest';

        $model = $this->loadModel($id);

        if ($key !== $model->activation_key) {
            throw new CHttpException(400, "Invalid activation key!");
        } else if ($key == null) {
            throw new CHttpException(400, "Invalid action!");
        }

        $model->scenario = 'activate';
        $model->activation_key = null;
        $model->save(false, array('activation_key'));

        $this->render('activation_success', array('model' => $model));
    }

    /**
     * generate a new password for the user.
     */
    public function actionResetPassword() {
        $this->layout = '//layouts/guest';

        $model = new PasswordResetForm;

        if (isset($_POST['PasswordResetForm'])) {
            $model->attributes = $_POST['PasswordResetForm'];
            if ($model->validate()) {
                $newPassword = $this->generateRandomString();

                $user = User::model()->findByAttributes(array('username' => $model->username));
                $user->password = $newPassword;

                if ($user->save()) {
                    Yii::app()->mailer->sendMail('NoteBuddy Account - Password Reset Information',
                        array(Yii::app()->params['adminEmail'] => 'Notebuddy Team'),
                        array($user->email,),
                        "$user->username, your new password is: $newPassword");

                    Yii::app()->user->setFlash('password-reset-success', "Your new password has been sent to your email.");
                    $this->refresh();
                }
            }
        }

        $this->render('password_reset', array('model' => $model));
    }

    /*
    * generate a random string. This is used by the resetPassword action.
    */
    private function generateRandomString($length = 9) {
        // makes a random alpha numeric string of a given length
        $aZ09 = array_merge(range('A', 'Z'), range('a', 'z'), range(0, 9));
        $out = '';
        for ($c = 0; $c < $length; $c++) {
            $out .= $aZ09[mt_rand(0, count($aZ09) - 1)];
        }
        return $out;
    }
}
